package controllers

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/your_username/backend-login-system/utils"
)

// GetProtectedData 处理获取受保护数据的请求，需要认证才能访问
func GetProtectedData(c *gin.Context) {
	// 从请求头中获取token
	tokenString := c.GetHeader("Authorization")
	if tokenString == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供授权令牌"})
		return
	}
	tokenString = strings.Replace(tokenString, "Bearer ", "", 1)

	token, err := utils.ParseJWT(tokenString)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的授权令牌"})
		return
	}

	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok || !token.Valid {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的授权令牌"})
		return
	}

	username := claims["username"].(string)
	// 这里可以根据用户名等信息获取对应的受保护数据，为简单起见，返回示例数据
	protectedData := map[string]interface{}{
		"message":  "这是受保护的数据，只有登录用户可访问",
		"username": username,
	}
	c.JSON(http.StatusOK, protectedData)
}
